#include "smart_sensor.h"
#include "setting.h"
#include <string.h>
#include <stdio.h>

#define  UPDATE_SENSOR_ERR	(-2)
#define  READ_PIR			(-1)
#define  NO_READ_PIR		(1)
#define  UPDATE_SENSOR_DONE	(2)

typedef struct
{
    uint8_t   sno;
    uint8_t   aid[AID_LEN];
    uint8_t   temp;
    uint8_t   humi;
    uint8_t   pir;
    uint32_t  lux;
    uint32_t  sun_light;
}sensor_device_t;
static sensor_device_t sensor_device[8];

static int read_sensor_flag,read_pir_flag;

//更新传感器档案
int update_sensor_archives(uint8_t addr[],int sno)
{
    if(sno>=0 && sno<=7)
    {
        printf("update %d sensor\n",sno);
        memcpy(setting.dev_infor.sensor_archives[sno],addr,AID_LEN);
        setting_save();
        return 1;
    }
    else
    {
        return -1;
    }
}


static int update_sensor_status(uint8_t *data, int len)
{
    int i=0;
    uint8_t sno;
    uint8_t frame_tail ;

    if(0== read_sensor_flag)
        return UPDATE_SENSOR_ERR;

check:
    while(i<len)
    {
        if(*(data+i) == 0x7E)
            break;
        i++;
    }

    if(i>=len)
        return UPDATE_SENSOR_ERR;

    sno = *(data+i+1);
    if(sno<1 || sno>8)//sno²»ÔÚ1-8Çø¼äÄÚ
    {
        i++;
        goto check;
    }

    frame_tail = ~(*(data+i+12));
    if(0x7E != frame_tail)//Ö¡Î²´íÎó
    {
        i++;
        goto check;
    }


    sensor_device[sno].lux = get_le_val(data+i+2,4);
    sensor_device[sno].sun_light = get_le_val(data+i+6,4);
    sensor_device[sno].temp = *(data+i+10);
    sensor_device[sno].humi = *(data+i+11);

    read_sensor_flag = 0;
    return UPDATE_SENSOR_DONE;
}
